package com.hexinfo.dmpro.dev.data.transfer.service.impl;

import cn.hutool.core.util.StrUtil;
import com.hexinfo.dmpro.component.file.transfer.model.FileTransfer;
import com.hexinfo.dmpro.component.file.transfer.service.FileTransferService;
import com.hexinfo.dmpro.dev.data.transfer.model.DevDataExportTask;
import com.hexinfo.dmpro.dev.data.transfer.service.ICleanFtpFileService;
import com.hexinfo.dmpro.dev.data.transfer.service.IDevDataExportTaskService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class CleanFtpFileServiceImpl implements ICleanFtpFileService {

    private final IDevDataExportTaskService devDataExportTaskService;

    @Value("${dev-data-clean-wait}")
    private Integer cleanWait;

    @Async
    @Override
    public void cleanFtpFile() {
        while (true) {
            try {
                Thread.sleep(cleanWait);
                List<DevDataExportTask> toDelList = getDelList();
                List<String> ids = toDelList.stream().map(DevDataExportTask::getId).collect(Collectors.toList());
                devDataExportTaskService.batchRemoveDataFileByIds(ids);
            } catch (Exception e) {
                log.error("删除FTP文件发生异常：{}", e.getMessage(), e);
            }
        }
    }

    /**
     * @Method getDelList
     * @Param
     * @Return java.util.List<com.hexinfo.dmpro.dev.data.transfer.model.DevDataExportTask>
     * @Description 获取需要删除ftp文件的清单
     * @Author Wang zhihao
     * @Date 2024/1/15 10:04
     * @Version V1.0
     */
    private List<DevDataExportTask> getDelList() {
        DevDataExportTask devDataExportTask = new DevDataExportTask().setIsDelDataFile("H");
        // 获取所有待删除ftp的任务
        List<DevDataExportTask> toDelDataFileList = devDataExportTaskService.queryListNoPage(devDataExportTask);
        // 过滤出del状态不为0的任务
        return toDelDataFileList;
    }

}
